package com.example.managemyself.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.provider.Settings;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;

/**
 * 位置服务诊断工具类
 * 用于诊断真机上位置服务相关问题
 */
public class LocationDiagnostic {
    
    private static final String TAG = "LocationDiagnostic";
    
    /**
     * 诊断结果类
     */
    public static class DiagnosticResult {
        public boolean hasLocationPermission;
        public boolean isGpsEnabled;
        public boolean isNetworkLocationEnabled;
        public boolean isGooglePlayServicesAvailable;
        public boolean isLocationModeOn;
        public String googlePlayServicesStatus;
        public String detailedReport;
        
        public boolean isLocationServiceUsable() {
            return hasLocationPermission && 
                   (isGpsEnabled || isNetworkLocationEnabled) && 
                   isLocationModeOn;
        }
    }
    
    /**
     * 执行完整的位置服务诊断
     */
    public static DiagnosticResult diagnose(Context context) {
        DiagnosticResult result = new DiagnosticResult();
        StringBuilder report = new StringBuilder();
        
        report.append("=== 位置服务诊断报告 ===\n\n");
        
        // 1. 检查位置权限
        result.hasLocationPermission = checkLocationPermissions(context);
        report.append("1. 位置权限检查: ")
              .append(result.hasLocationPermission ? "✓ 已授予" : "✗ 未授予")
              .append("\n");
        
        if (!result.hasLocationPermission) {
            report.append("   - 精确位置权限: ")
                  .append(ContextCompat.checkSelfPermission(context, 
                         Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ? "已授予" : "未授予")
                  .append("\n");
            report.append("   - 粗略位置权限: ")
                  .append(ContextCompat.checkSelfPermission(context, 
                         Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ? "已授予" : "未授予")
                  .append("\n");
        }
        
        // 2. 检查位置服务状态
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        
        result.isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        result.isNetworkLocationEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        
        report.append("\n2. 位置提供者状态:\n");
        report.append("   - GPS提供者: ")
              .append(result.isGpsEnabled ? "✓ 已启用" : "✗ 已禁用")
              .append("\n");
        report.append("   - 网络提供者: ")
              .append(result.isNetworkLocationEnabled ? "✓ 已启用" : "✗ 已禁用")
              .append("\n");
        
        // 3. 检查系统位置模式
        try {
            int locationMode = Settings.Secure.getInt(context.getContentResolver(), 
                                                     Settings.Secure.LOCATION_MODE);
            result.isLocationModeOn = locationMode != Settings.Secure.LOCATION_MODE_OFF;
            
            report.append("\n3. 系统位置模式: ");
            switch (locationMode) {
                case Settings.Secure.LOCATION_MODE_OFF:
                    report.append("✗ 已关闭");
                    break;
                case Settings.Secure.LOCATION_MODE_SENSORS_ONLY:
                    report.append("✓ 仅设备传感器(GPS)");
                    break;
                case Settings.Secure.LOCATION_MODE_BATTERY_SAVING:
                    report.append("✓ 省电模式(仅网络)");
                    break;
                case Settings.Secure.LOCATION_MODE_HIGH_ACCURACY:
                    report.append("✓ 高精度模式(GPS + 网络 + WiFi)");
                    break;
                default:
                    report.append("? 未知模式 (").append(locationMode).append(")");
            }
            report.append("\n");
        } catch (Settings.SettingNotFoundException e) {
            result.isLocationModeOn = false;
            report.append("\n3. 系统位置模式: ✗ 无法检测\n");
        }
        
        // 4. 检查Google Play Services
        GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
        int playServicesStatus = googleApiAvailability.isGooglePlayServicesAvailable(context);
        result.isGooglePlayServicesAvailable = playServicesStatus == ConnectionResult.SUCCESS;
        
        report.append("\n4. Google Play Services:\n");
        switch (playServicesStatus) {
            case ConnectionResult.SUCCESS:
                result.googlePlayServicesStatus = "可用";
                report.append("   - 状态: ✓ 可用且最新");
                break;
            case ConnectionResult.SERVICE_MISSING:
                result.googlePlayServicesStatus = "缺失";
                report.append("   - 状态: ✗ 未安装");
                break;
            case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
                result.googlePlayServicesStatus = "需要更新";
                report.append("   - 状态: ⚠ 需要更新");
                break;
            case ConnectionResult.SERVICE_DISABLED:
                result.googlePlayServicesStatus = "已禁用";
                report.append("   - 状态: ✗ 已禁用");
                break;
            default:
                result.googlePlayServicesStatus = "其他错误: " + playServicesStatus;
                report.append("   - 状态: ✗ 错误代码: ").append(playServicesStatus);
        }
        report.append("\n");
        
        // 5. 检查可用的位置提供者
        report.append("\n5. 可用的位置提供者:\n");
        for (String provider : locationManager.getAllProviders()) {
            boolean isEnabled = locationManager.isProviderEnabled(provider);
            report.append("   - ").append(provider).append(": ")
                  .append(isEnabled ? "✓ 启用" : "✗ 禁用")
                  .append("\n");
        }
        
        // 6. 综合评估
        report.append("\n=== 综合评估 ===\n");
        if (result.isLocationServiceUsable()) {
            report.append("✓ 位置服务可用，应该能够正常获取位置信息");
        } else {
            report.append("✗ 位置服务不可用，存在以下问题:\n");
            if (!result.hasLocationPermission) {
                report.append("   - 缺少位置权限\n");
            }
            if (!result.isLocationModeOn) {
                report.append("   - 系统位置服务已关闭\n");
            }
            if (!result.isGpsEnabled && !result.isNetworkLocationEnabled) {
                report.append("   - 所有位置提供者都已禁用\n");
            }
        }
        
        // 7. 建议解决方案
        report.append("\n=== 建议解决方案 ===\n");
        if (!result.hasLocationPermission) {
            report.append("• 在应用设置中授予位置权限\n");
        }
        if (!result.isLocationModeOn) {
            report.append("• 在系统设置中开启位置服务\n");
        }
        if (!result.isGpsEnabled && !result.isNetworkLocationEnabled) {
            report.append("• 在位置设置中启用GPS或网络定位\n");
        }
        if (!result.isGooglePlayServicesAvailable) {
            if (playServicesStatus == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
                report.append("• 更新Google Play Services到最新版本\n");
            } else if (playServicesStatus == ConnectionResult.SERVICE_MISSING) {
                report.append("• 安装Google Play Services\n");
            } else if (playServicesStatus == ConnectionResult.SERVICE_DISABLED) {
                report.append("• 启用Google Play Services\n");
            }
        }
        
        result.detailedReport = report.toString();
        
        Log.i(TAG, result.detailedReport);
        return result;
    }
    
    /**
     * 检查位置权限
     */
    private static boolean checkLocationPermissions(Context context) {
        return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
               ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }
    
    /**
     * 获取简化的状态报告
     */
    public static String getSimpleStatus(Context context) {
        DiagnosticResult result = diagnose(context);
        StringBuilder status = new StringBuilder();
        
        status.append("位置权限: ").append(result.hasLocationPermission ? "已授予" : "未授予").append("\n");
        status.append("GPS: ").append(result.isGpsEnabled ? "已启用" : "已禁用").append("\n");
        status.append("网络定位: ").append(result.isNetworkLocationEnabled ? "已启用" : "已禁用").append("\n");
        status.append("Google Play Services: ").append(result.googlePlayServicesStatus).append("\n");
        status.append("整体状态: ").append(result.isLocationServiceUsable() ? "可用" : "不可用");
        
        return status.toString();
    }
} 